package cn.invest.merry.module.invest.service;

import cn.invest.merry.framework.common.util.json.JsonUtils;
import cn.invest.merry.module.invest.config.JuchaoConfig;
import cn.invest.merry.module.invest.dal.dataobject.gsbase.GsBaseDO;
import cn.invest.merry.module.invest.dal.dataobject.lrbase.LrBaseDO;
import cn.invest.merry.module.invest.dal.dataobject.xjbase.XjBaseDO;
import cn.invest.merry.module.invest.dal.dataobject.zbbase.ZbBaseDO;
import cn.invest.merry.module.invest.dal.dataobject.zcfzbase.ZcfzBaseDO;
import cn.invest.merry.module.invest.dal.mysql.gsbase.GsBaseMapper;
import cn.invest.merry.module.invest.dal.mysql.lrbase.LrBaseMapper;
import cn.invest.merry.module.invest.dal.mysql.xjbase.XjBaseMapper;
import cn.invest.merry.module.invest.dal.mysql.zbbase.ZbBaseMapper;
import cn.invest.merry.module.invest.dal.mysql.zcfzbase.ZcfzBaseMapper;
import cn.invest.merry.module.invest.service.vo.BaseVo;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.JsonNode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;

/**
 * 初始数据Service业务层处理
 * 
 * @author tz
 * @date 2022-11-20
 */
@Service
public class JuchaoServiceImpl
{
    @Autowired
    private JuchaoConfig config;
    @Autowired
    private GsBaseMapper gsBaseMapper;
    @Autowired
    private ZcfzBaseMapper zcfzBaseMapper;
    @Autowired
    private LrBaseMapper lrBaseMapper;
    @Autowired
    private XjBaseMapper xjBaseMapper;
    @Autowired
    private ZbBaseMapper zbBaseMapper;
    public boolean initGsBaseFromJuchao(BaseVo baseVo) {
        //同步基本信息
        List<GsBaseDO> list = syncCommon(config.getGsjbxx(), GsBaseDO.class, baseVo);
        gsBaseMapper.insertOrUpdateBatch(list);
        //同步资产负债
        List<ZcfzBaseDO> listZcfz = syncCommon(config.getZcfz(), ZcfzBaseDO.class, baseVo);
        zcfzBaseMapper.insertOrUpdateBatch(listZcfz);
        //同步利润
        List<LrBaseDO> listLr = syncCommon(config.getLr(), LrBaseDO.class, baseVo);
        lrBaseMapper.insertOrUpdateBatch(listLr);
        //同步现金
        List<XjBaseDO> listXj = syncCommon(config.getXj(), XjBaseDO.class, baseVo);
        xjBaseMapper.insertOrUpdateBatch(listXj);
        //同步指标
        List<ZbBaseDO> listZb = syncCommon(config.getZb(), ZbBaseDO.class, baseVo);
        zbBaseMapper.insertOrUpdateBatch(listZb);
        return true;
    }

    /**
     * 通用
     * @param uri
     * @param clazz
     * @param baseVo
     * @return
     */
    public List syncCommon(String uri, Class clazz, BaseVo baseVo) {
        //每一只股票的返回的数据不超过500，不用分页了
        String token= getToken();  //请在平台注册后并填入个人中心-我的凭证中的Access Key，Access Secret
        StringBuffer url= new StringBuffer();
        url.append(config.getHost()+uri).append("?&access_token="+token);
        url.append(baseVo.getParam());
        //接口名、参数名、参数值请按实际情况填写
        String page = getPage(url.toString(),"utf-8") ;
        JsonNode json = JsonUtils.parseTree(page);
        int resultcode = json.findValue("resultcode").asInt();
        if(resultcode == 200){
            return JsonUtils.parseArray(page, "records", clazz);
        }else{
            throw new RuntimeException("同步出错");
        }
    }
    @Cacheable(value = "juchao_token")
    public String getToken() {
        String strURL = config.getHost() + config.getToken();
        String params = "grant_type=client_credentials&client_id="+ config.getAccessKey() +"&client_secret="+config.getAccessSecret();
        try {
            URL url = new URL(strURL);// 创建连接
            HttpURLConnection connection = (HttpURLConnection) url
                    .openConnection();
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setUseCaches(false);
            connection.setInstanceFollowRedirects(true);
            connection.setRequestMethod("POST"); // 设置请求方式
            connection.connect();
            OutputStreamWriter out = new OutputStreamWriter(
                    connection.getOutputStream(), "UTF-8"); // utf-8编码
            out.append(params);
            out.flush();
            out.close();
            try{
                BufferedReader reader = new BufferedReader(new InputStreamReader(
                        connection.getInputStream()));

                String lines;
                String jsonString = "";
                while ((lines = reader.readLine()) != null) {
                    lines = new String(lines.getBytes(), "utf-8");
                    jsonString+=lines;
                }
                System.out.println(jsonString);
                JSONObject jb = JSONObject.parseObject(jsonString);
                String access_token = "";
                access_token=jb.getString("access_token");
                reader.close();
                return access_token;
            }catch(IOException e1)
            {
                e1.printStackTrace();
                return "error";
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return "error"; // 自定义错误信息
    }

    public String getPage(String tempurl,String bm) {
        String result="";
        try {
            URL url = new URL(tempurl);
            InputStream is = null;
            URLConnection con=url.openConnection();
            con.addRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
            con.setConnectTimeout(120000);
            con.setReadTimeout(120000);
            con.connect();
            try {
                is = con.getInputStream();
                BufferedReader reader = null;
                try {
                    reader = new BufferedReader(new InputStreamReader(is,bm));
                    String s="";
                    String linesep = System.getProperty("line.separator");
                    while((s = reader.readLine())!=null){//使用readLine方法，一次读一行
                        result += s+linesep ;
                    }
                    reader.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }finally {
                    if (reader != null) {
                        try {
                            reader.close();
                        } catch (Exception e1) {
                        }
                    }
                }
                is.close();
            }catch (FileNotFoundException e2) {
                ;
            }
        } catch (Exception e1) {
            e1.printStackTrace();
        }
        return result;
    }
}
